<template>
  <div class="code-editor" ref="editorRef"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { EditorView, basicSetup } from 'codemirror'
import { EditorState } from '@codemirror/state'
import { javascript } from '@codemirror/lang-javascript'
import { html } from '@codemirror/lang-html'
import { json } from '@codemirror/lang-json'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'html'
  }
})

const emit = defineEmits(['update:modelValue'])

const editorRef = ref(null)
let editor = null

const getLanguageSupport = (lang) => {
  switch (lang) {
    case 'javascript':
      return javascript()
    case 'html':
      return html()
    case 'json':
      return json()
    default:
      return javascript()
  }
}

const initEditor = () => {
  if (!editorRef.value) return

  const state = EditorState.create({
    doc: props.modelValue,
    extensions: [
      basicSetup,
      getLanguageSupport(props.language),
      EditorView.updateListener.of((update) => {
        if (update.docChanged) {
          emit('update:modelValue', update.state.doc.toString())
        }
      })
    ]
  })

  editor = new EditorView({
    state,
    parent: editorRef.value
  })
}

watch(() => props.modelValue, (newValue) => {
  if (editor && newValue !== editor.state.doc.toString()) {
    editor.dispatch({
      changes: {
        from: 0,
        to: editor.state.doc.length,
        insert: newValue
      }
    })
  }
})

watch(() => props.language, () => {
  if (editor) {
    editor.destroy()
    initEditor()
  }
})

onMounted(() => {
  initEditor()
})

onBeforeUnmount(() => {
  if (editor) {
    editor.destroy()
  }
})
</script>

<style scoped>
.code-editor {
  height: 100%;
  width: 100%;
}

:deep(.cm-editor) {
  height: 100%;
  font-size: 14px;
}

:deep(.cm-scroller) {
  font-family: 'Fira Code', monospace;
}
</style> 